package com.dlc.garbagerecyclebox.core;

import android.util.ArrayMap;
import android.util.Log;

import com.dlc.commonbiz.base.callback.CommonCallback;
import com.dlc.commonbiz.base.exception.BaseSerialPortException;
import com.dlc.commonbiz.base.serialport.CmdPack;
import com.dlc.commonbiz.base.util.GsonUtil;
import com.dlc.commonbiz.base.util.RxUtil;
import com.dlc.commonbiz.base.util.SharedPreferencesUtil;
import com.dlc.garbagerecyclebox.GarbageRecyclerBoxCmdProxy;
import com.dlc.garbagerecyclebox.IOType;
import com.dlc.garbagerecyclebox.SwitchType;
import com.dlc.garbagerecyclebox.bean.BoxErrorInfo;
import com.dlc.garbagerecyclebox.bean.ControlBean;
import com.dlc.garbagerecyclebox.bean.DeviceInfoBean;
import com.dlc.garbagerecyclebox.bean.HeartBeatBean;
import com.dlc.garbagerecyclebox.bean.ManageMaintainInfoBean;
import com.dlc.garbagerecyclebox.log.GarbageRecycleBoxLogFactory;

import java.util.Calendar;

/**
 * author: Administrator
 * create time: 2019/8/31 22:15
 * description:
 * 箱子操作管理
 */
public class BoxMgr {
    private static class SingletonHolder {
        private static final BoxMgr INSTANCE = new BoxMgr();
    }

    private BoxMgr() {

    }

    public static final BoxMgr getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private ArrayMap<String, BoxErrorInfo> listFull = new ArrayMap<>();

    /**
     * 控制开关灯
     *
     * @param heart
     */
    public void controlLight(final HeartBeatBean heart) {

        if (heart != null && heart.getSensorStatusBean() != null) {
            final DeviceInfoBean.SensorStatusBean sensorStatusBean = heart.getSensorStatusBean();
            ControlBean controlBean = getControlBean();
            BoxErrorInfo boxErrorInfo = null;
            if (listFull.containsKey(heart.getDeviceAddress() + "")) {
                boxErrorInfo =listFull.get(heart.getDeviceAddress() + "");
            }
            boolean isMoreTemperature = false;
            if (boxErrorInfo != null) {
                isMoreTemperature = boxErrorInfo.isTempError;
            }
//            if (controlBean != null) {
//                isMoreTemperature = controlBean.moreTemperature(sensorStatusBean.getTemperatureValue());
            //判断是否有烟感和温度是否过高,y要开风扇
            if (isMoreTemperature) {
                //温度过高或烟感报警，开风扇
                if (!sensorStatusBean.isFanInBox()) {
                    Log.d("Heart_beat", "打开风扇");
                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Open, IOType.FanInBox);
                }
            } else {
                //故障消失,关闭风扇
                if (sensorStatusBean.isFanInBox()) {
                    Log.d("Heart_beat", "关闭风扇");
                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Shut, IOType.FanInBox);
                }
            }
//            }
            boolean isOpenLight = false;
            if (controlBean != null) {
                isOpenLight = judgeIsIn(controlBean.getOpenLight(), controlBean.getOffLight());
            }
            //如果故障或者烟感触发
            if (heart.getFaultCodeBean() != null && heart.getFaultCodeBean().isFault()
                    || sensorStatusBean.isSmokeSensing() || isMoreTemperature) {
                if (sensorStatusBean.isBoxTopIndicatorBlue() || sensorStatusBean.isBoxTopIndicatorGreen() ||
                        !sensorStatusBean.isBoxTopIndicatorRed()) {
                    //关掉白灯
                    GarbageRecycleBoxLogFactory.info("关闭白灯");
                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Shut, IOType.BoxTopIndicatorWhite);
                    RxUtil.getInstance().delayMillisecondsRx(200, new RxUtil.DelayCallback() {
                        @Override
                        public void onComplete() {
                            //如果开启红灯
                            GarbageRecycleBoxLogFactory.info("开启红灯");
                            openLightOrClose(heart.getDeviceAddress(), SwitchType.Open, IOType.BoxTopIndicatorRed);
                        }
                    });
                }
            } else {
                boolean isFull = false;
                if (boxErrorInfo != null) {
                    isFull = boxErrorInfo.isFull;
                    if (isFull) {
                        openLightOrClose(heart.getDeviceAddress(), SwitchType.Shut, IOType.BoxTopIndicatorWhite);
                        RxUtil.getInstance().delayMillisecondsRx(200, new RxUtil.DelayCallback() {
                            @Override
                            public void onComplete() {
                                //开启蓝灯
                                GarbageRecycleBoxLogFactory.info("开启蓝灯");
                                openLightOrClose(heart.getDeviceAddress(), SwitchType.Open, IOType.BoxTopIndicatorBlue);
                            }
                        });
                    }
                }
                if (!isFull) {
                    if (isOpenLight) {
                        if (!sensorStatusBean.isBoxTopIndicatorWhite()) {
                            //关掉白灯
                            Log.d("Heart_beat", "关闭白灯");
                            openLightOrClose(heart.getDeviceAddress(), SwitchType.Shut, IOType.BoxTopIndicatorWhite);
                            RxUtil.getInstance().delayMillisecondsRx(200, new RxUtil.DelayCallback() {
                                @Override
                                public void onComplete() {
                                    //开启白灯
                                    GarbageRecycleBoxLogFactory.info("开启白灯");
                                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Open, IOType.BoxTopIndicatorWhite);
                                }
                            });
                        }
                    } else {
                        if (sensorStatusBean.isBoxTopIndicatorRed()
                                || sensorStatusBean.isBoxTopIndicatorGreen()
                                || sensorStatusBean.isBoxTopIndicatorBlue()) {
                            GarbageRecycleBoxLogFactory.info("关闭白灯");
                            openLightOrClose(heart.getDeviceAddress(), SwitchType.Shut, IOType.BoxTopIndicatorWhite);
                        }

                    }
                }

            }
            if (isOpenLight) {
                if (!sensorStatusBean.isOpenExteriorLights()) {
                    GarbageRecycleBoxLogFactory.info("打开外部照明灯");
                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Open, IOType.ExteriorLights);
                }
                if (!sensorStatusBean.isOpenAdvertisingLights()) {
                    GarbageRecycleBoxLogFactory.info("打开广告灯（顶部+侧面）");
                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Open, IOType.AdvertisingLights);
                }
            } else {
                if (sensorStatusBean.isOpenExteriorLights()) {
                    GarbageRecycleBoxLogFactory.info("关闭外部照明灯");
                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Shut, IOType.ExteriorLights);
                }
                if (sensorStatusBean.isOpenAdvertisingLights()) {
                    GarbageRecycleBoxLogFactory.info("关闭广告灯（顶部+侧面）");
                    openLightOrClose(heart.getDeviceAddress(), SwitchType.Shut, IOType.AdvertisingLights);
                }
            }
            //Log.d("Heart_beat",
            //    "aa==d地址" + heart.getDeviceAddress() + ",  温度=" + sensorStatusBean.getTemperatureValue() + ",  故障=" + (heart.getFaultCodeBean()
            //        != null && heart.getFaultCodeBean().isFault()) + ", isSmoke==" + sensorStatusBean.isSmokeSensing());

        }
    }

    private void openLightOrClose(int address, @SwitchType int switchType, @IOType int ioType) {
        Log.d("lgq","开灯命令100-00000-1166----"+address+"......."+switchType);
        GarbageRecyclerBoxCmdProxy.get().ioPortControlCommand(address, ioType, switchType, new CommonCallback<ManageMaintainInfoBean>() {
            @Override
            public void onStart(CmdPack cmdPack) {
                GarbageRecycleBoxLogFactory.info(cmdPack.toString());
            }

            @Override
            public void onSuccess(ManageMaintainInfoBean recyclingInfoBean) {
                GarbageRecycleBoxLogFactory.info("IO口控制命令:" + recyclingInfoBean.toString());
            }

            @Override
            public void onFailed(BaseSerialPortException dLCException) {
                GarbageRecycleBoxLogFactory.info("IO口控制命令-->失败:" + dLCException.toString());
            }
        });
    }

    public ControlBean getControlBean() {
        return GsonUtil.getInstance().parseJsonStrToObj(SharedPreferencesUtil.getDefault().getString("control_bean", null), ControlBean.class);
    }

    public void saveControlBean(ControlBean bean) {
        if (bean == null) {
            SharedPreferencesUtil.getDefault().edit().remove("control_bean").apply();
        } else {
            SharedPreferencesUtil.getDefault().edit().putString("control_bean", GsonUtil.getInstance().parseObjToJsonStr(bean)).apply();
        }
    }

    /**
     * 溢满上报
     *
     * @param address
     */
    public void setFull(String address, BoxErrorInfo boxErrorInfo) {
        listFull.put(address, boxErrorInfo);
    }

    /**
     * 判断当前时间是否在某个范围之内
     *
     * @param starttime 8:00
     * @param endtime   10:00
     */
    private boolean judgeIsIn(String starttime, String endtime) {
        //0.获取当前时间
        Calendar instance = Calendar.getInstance();
        int hourOfDay = instance.get(Calendar.HOUR_OF_DAY);
        int minuteOfDay = instance.get(Calendar.MINUTE);

        //2.判断是否在规定的小时以内
        String[] startSplit = starttime.split(":");
        int startHour = Integer.parseInt(startSplit[0]);
        int startMinute = Integer.parseInt(startSplit[1]);
        String[] endSplit = endtime.split(":");
        int endHour = Integer.parseInt(endSplit[0]);
        int endMinute = Integer.parseInt(endSplit[1]);
        if (hourOfDay < startHour || hourOfDay > endHour) {
            return false;
        }
        //3.判断是否在规定的分钟内
        if (hourOfDay == startHour && minuteOfDay < startMinute) {
            return false;
        }
        if (hourOfDay == endHour && minuteOfDay > endMinute) {
            return false;
        }
        return true;
    }
}
